/**
 * 设置个人资料接口
 */

//引入Q模块
let Q = require('q');
//引入公共函数
let util = require('../../util');

//setMyRoleInfo接口入口文件
let index = function(getData, postData, config, redis, db) {
	let deferred = Q.defer();
	if(postData.infoId && postData.infoVal) {
		if(postData.infoId == 'tableNums' && postData.infoVal != '*') {
			let tableNums = [];
			let tableNumsArr = postData.infoVal.replace(/\s+/g, '').replace('，', ',').split(',');
			for(let tableNumIndex in tableNumsArr) {
				if(tableNumsArr[tableNumIndex].indexOf('-') == -1) {
					tableNums.push(tableNumsArr[tableNumIndex]);
				}
				else {
					let temp = tableNumsArr[tableNumIndex].split('-');
					if(temp[0].length > 0 && temp[1].length > 0) {
						let num = temp[0].replace(/[^0-9]/ig, "");
						let prefix = temp[0].substr(0, temp[0].indexOf(num));
						for(let i = parseInt(num);i < parseInt(temp[1]) + 1;i++) {
							tableNums.push(prefix + i);
						}
					}
					else {
						deferred.reject();
						return deferred.promise;
					}
				}
			}
			postData.infoVal = tableNums;
		}
		redis.get(postData._3rdSession).then(function(data) {
			data = JSON.parse(data).openId;
			let updateData = {};
			updateData[postData.infoId] = postData.infoVal;
			return db.update('allowServices', {
				id: data
			}, updateData);
		}, function() {
			//从redis读取3rsSession失败
			deferred.reject('-0003');
		}).then(function() {
			deferred.resolve(1);
		}, function() {
			//更改允许服务员资料失败
			deferred.reject('-0164'); 
		});
	}
	else {
		//设置个人资料接口参数不足
		deferred.reject('-0163');
	}
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
}